import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		userInfo: uni.getStorageSync('userInfo') || {},
		content: '',
		withdrawSetting: {},
		address: null,
		token: '',
		lock: 0,
		updateLock: 0,
	},
	getters: {
		pid: state => state.userInfo && state.userInfo.pid || 0,
	},
	mutations: {
		SETAUDIO(state, provider) {
			state.audio = provider
		},
		saveuserinfo(state, provider) {
			state.userInfo = provider
			uni.setStorage({
				key: 'userInfo',
				data: provider
			})
		},
		selectaddress(state, provider) {
			state.address = provider
		},
		save(state, provider) {
			state.content = provider
		},
		withdrawsetting(state, provider) {
			state.withdrawSetting = provider
		},
		logout(state) {
			state.userInfo = {}
			uni.setStorage({
				key: 'userInfo',
				data: {}
			})
			uni.setStorage({
				key: 'auth',
				data: null
			})
		},
		SETTOKEN(state, provider) {
			state.token = provider
			uni.setStorage({
				key: 'token',
				data: provider
			})
		},

	},
	actions: {
		async handleGetUtrace({
			commit,
			dispatch,
			state
		}) {
			if (state.requestLock.request) {
				return await state.requestLock.request;
			}
			state.requestLock.status = true
			state.requestLock.count += 1
			state.requestLock.request = new Promise(async (resolve, reject) => {
				if (state.utrace) {
					return resolve(state.utrace)
				}
				let utrace = uni.getStorageSync('utrace')
				if (utrace) {
					return resolve(utrace)
				}
				try {
					const openid = await dispatch('handleGetOpenId')
					let that = getApp().$vm.$track
					that.setUtrace(openid)
					// 阿拉丁上报openId
					wx.aldstat.sendOpenid(openid)
					let utrace = that.getUtrace()
					commit('SETUTRACE', utrace)
					state.requestLock.count = 0
					resolve(utrace)
				} catch (e) {
					reject(e)
				} finally {
					state.requestLock.status = false;
					state.requestLock.request = null;
				}
			})
			return await state.requestLock.request
		},

	}
})

export default store
